<template>
  <div class="login-container">
    <!-- 导航栏 -->
    <van-nav-bar title="登录"/>
    <!-- /导航栏 -->

    <!-- 登录表单 -->
    <van-form @submit="onsubmit">
      <van-field
        :rules="userRules.mobile"
        v-model="user.mobile"
        name="username"
        type="number"
        maxlength="11"
        placeholder="请输入手机号">
        <i slot="left-icon" class="toutiao iconshouji"></i>
      </van-field>
      <van-field
        :rules="userRules.code"
        v-model="user.code"
        type="number"
        maxlength="6"
        placeholder="请输入验证码">
        <i slot="left-icon" class="toutiao iconyanzhengma"></i>
        <template #button>
          <van-button class="send-code" size="small" type="primary">发送验证码</van-button>
        </template>
      </van-field>
      <div class="login-btn-wrap">
        <van-button class="login-btn" round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
    <!-- /登录表单 -->
  </div>
</template>

<script>
import { login } from '@/api/user'
export default {
  data () {
    return {
      name: 'Login',
      // 用户表单数据
      user: {
        mobile: '18900000000',
        code: '246810'
      },
      // 校验规则
      userRules: {
        mobile: [
          { required: true, message: '请填写手机号' },
          { pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/, message: '手机号码格式不正确' }
        ],
        code: [
          { required: true, message: '请填写验证码' },
          { pattern: /^\d{6}$/, message: '验证码格式不正确' }
        ]
      }
    }
  },

  created () {

  },

  methods: {
    // 提交表单
    async onsubmit () {
      // 登录成功后 loading 会被移除
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      })
      try {
        const res = await login(this.user)
        console.log('登陆成功', res)
        this.$toast.success('登录成功')
      } catch (err) {
        if (err.response.status === 400) {
          console.log('手机号或验证码错误')
          this.$toast.fail('手机号或验证码错误')
        } else {
          console.log('系统错误')
          this.$toast.fail('系统错误')
        }
      }
    }
  }
}
</script>

<style scoped lang='less'>
.login-container {
    .toutiao {
        font-size: 37px;
    }

    .send-code {
      width: 172px;
      height: 46px;
      line-height: 46px;
      background-color: #ededed;
      font-size: 22px;
      color: #666;
      border-color: #ededed;
      border-radius: 23px;
    }

    .login-btn-wrap {
    padding: 53px 33px;
    .login-btn {
      background-color: #6db4fb;
      border: none;
      border-radius: 10px;
    }
  }

}
</style>
